<script setup lang="ts">
import {watch, ref, reactive, nextTick,onBeforeUnmount} from "vue";
import {reqAttr, reqAddOrUpdateAttr,reqRemoveAttr} from "@/api/product/attr";
//获取分类的仓库
import useCategoryStore from '@/store/modules/category'
import {AttrResponseData, Attr, AttrValue} from "@/api/product/attr/type.ts";
import {ElMessage} from "element-plus";

let categoryStore = useCategoryStore()
let attrArr = ref<Attr[]>([])
//定义card组件内容切换变量
let scene = ref<number>(0) //0表示属性列表 1表示属性添加分组

//收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '', //属性名称
  attrValueList: [], //属性值的数组
  categoryId: '', //三级分类的ID
  categoryLevel: 3 //默认是三级分类
})

//准备数组：每一个input框将其存入inputArr数组中
let inputArr = ref<any>([])

//监听三级分类的变化
watch(() => categoryStore.c3Id, () => {
  //清空上一次查询的属性和属性值
  attrArr.value = []
  //保证三级分类得有才发送请求
  if (!categoryStore.c3Id) return
  getAttr()
})
//获取已有的属性和属性值方法
const getAttr = async () => {
  const {c1Id, c2Id, c3Id} = categoryStore
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code === 200) {
    attrArr.value = result.data
  }
}


//修改属性
const updateAttr = (row:Attr) => {
    scene.value = 1
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
}


//删除某一个已有的属性方法回调
const deleteAttr = async (attrId: number) => {
  //发相应的删除已有的属性的请求
  let result: any = await reqRemoveAttr(attrId)
  //删除成功
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //获取一次已有的属性与属性值
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

const cancel = () => {
  scene.value = 0
}

//添加属性
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.c3Id,
    categoryLevel: 3
  })
  scene.value = 1
}
//添加属性值
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true //true表示编辑模式 false表示查看模式s
  })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
//保存属性和属性值
const save = async () => {
  let result: any = await reqAddOrUpdateAttr(attrParams)
  if (result.code === 200) {
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功'
    })
    await getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败'
    })
  }
}

//编辑模式与查看模式的切换
const toLook = (row: AttrValue,$index:number) => {
  //非法情况判断1
  if (row.valueName.trim() == '') {
    //删除调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }

  //非法情况2
  let repeat = attrParams.attrValueList.find((item) => {
    //切记把当前失去焦点属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    //将重复的属性值从数组当中干掉
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  row.flag = false
}
//编辑模式与查看模式的切换
const toEdit = (row: AttrValue,$index:number) => {
  row.flag = true
  //nextTick:响应式数据发生变化,获取更新的DOM(组件实例)
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  //清空仓库的数据
  categoryStore.$reset()
})
</script>

<template>
  <!--  三级分类全局组件-->
  <Category :scene="scene"/>

  <el-card style="margin: 10px 0">
    <div v-show="scene===0">
      <el-button type="primary" size="default" icon="Plus" :disabled="!categoryStore.c3Id" @click="addAttr">添加属性
      </el-button>
      <el-table border style="margin: 10px 0" :data="attrArr">
        <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
        ></el-table-column>
        <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{row}">
            <el-tag style="margin:5px;" v-for="item in row.attrValueList" :key="item.id">
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{row}">
            <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>

            <el-popconfirm :title="`你确认删除${row.attrName}?`" width="200px" @confirm="deleteAttr(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene ===1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" size="default" icon="Plus" :disabled="!attrParams.attrName" @click="addAttrValue">
        添加属性值
      </el-button>
      <el-button type="primary" size="default" @click="cancel">
        取消
      </el-button>
      <el-table border style="margin: 10px 0" :data="attrParams.attrValueList">
        <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{row,$index}">
            <el-input  :ref="(vc:any)=>inputArr[$index] =vc"    placeholder="请输入属性值名称" v-if="row.flag" v-model="row.valueName" @blur="toLook(row,$index)"></el-input>
            <div v-else @click="toEdit(row,$index)">{{row.valueName}}</div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作" width="120px">
          <template #="{row,$index}">
            <el-button type="danger" size="small" icon="Delete" @click="attrParams.attrValueList.splice($index,1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" size="default" @click="save" :disabled="attrParams.attrValueList.length<=0">保存</el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>

    </div>
  </el-card>


</template>

<style scoped>

</style>